package com.du.spring.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author : DuJiabao
 * @Date : 2021/3/18 14:04
 * @Project : spring
 * @File : null.java
 * @Desc :
 */
@Configuration
@ComponentScan(basePackages = "com.du.spring") // 组件扫描
@EnableTransactionManagement  // 开启事务管理器
public class TxConfig {
  // 实例化bean并返回
  @Bean
  public DruidDataSource getDruidDataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&rewriteBatchedStatements=true");
    dataSource.setUsername("root");
    dataSource.setPassword("root");
    return dataSource;
  }

  @Bean
  public JdbcTemplate getJdbcTemplate(DruidDataSource dataSource) {  // 将需要配置的对象放在形参中，会autowired到里面
    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    jdbcTemplate.setDataSource(dataSource);
    return jdbcTemplate;
  }

  @Bean
  public DataSourceTransactionManager getDataSourceTransactionManager(DruidDataSource dataSource) {
    DataSourceTransactionManager manager = new DataSourceTransactionManager();
    manager.setDataSource(dataSource);
    return manager;
  }
}
